package com.intelligentmeterreadingsys.httpserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;

import android.content.Context;

import com.intelligentmeterreadingsys.util.SharedPreferenceUtil;

import dbhelper.XmlNameHelper;

public class HttpClientServer {

    public Context context;

    public String urlAddress;

    public String request;
    private SharedPreferenceUtil sp;

    public HttpClientServer(Context context) {

	this.context = context;
	sp = new SharedPreferenceUtil(context);

    }

    /**
     * 创建HttpClient 并设置参数
     * 
     * @param timeout
     * @return
     */
    public HttpClient getHttpClient() {
	BasicHttpParams httpParams = new BasicHttpParams();
	// 设置请求超时时间
	HttpConnectionParams.setConnectionTimeout(httpParams, 10 * 1000);
	HttpConnectionParams.setSoTimeout(httpParams, 10 * 1000);// 设置等待数据超时时间
	// 设置 Socket 缓存大小
	HttpConnectionParams.setSocketBufferSize(httpParams, 8192);
	HttpClient client = new DefaultHttpClient(httpParams);
	return client;
    }

    /**
     * 发送普通Http请求
     * 
     * @param user
     * @return
     */
    public String doPost(Map<String, String> map, String request) {
	geturl(request);

	HttpPost httpPost = new HttpPost(urlAddress);
	System.out.println(urlAddress);
	List params = new ArrayList();
	for (String key : map.keySet()) {
	    System.out.println("key:" + key + ":value:" + map.get(key));
	    NameValuePair pair = new BasicNameValuePair(key, map.get(key));
	    params.add(pair);
	}
	HttpEntity he;
	try {
	    he = new UrlEncodedFormEntity(params, "utf-8");

	    httpPost.setEntity(he);

	    HttpClient hc = getHttpClient();

	    HttpResponse ht = hc.execute(httpPost);

	    if (ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
		HttpEntity het = ht.getEntity();
		System.out.println((int) het.getContentLength());
		InputStream is = het.getContent();

		return getInputStreamString(is);
	    } else {
		System.out.println("---------------------");
		return "error";
	    }

	} catch (Exception e) {
	    e.printStackTrace();
	    return "error";
	}

    }

    /**
     * 通过输入流得到返回的字符串
     * 
     * @param is
     * @return
     */
    public String getInputStreamString(InputStream is) {
	BufferedReader br = null;
	InputStreamReader isr = null;
	byte[] by = new byte[64];
	String str = "";
	String res = "";
	if (is != null) {

	    try {
		isr = new InputStreamReader(is, "utf-8");
		br = new BufferedReader(isr);
		while ((res = br.readLine()) != null) {
		    str = str + res;
		}

	    } catch (UnsupportedEncodingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    } catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    } finally {

		if (is != null) {
		    try {
			br.close();
			isr.close();
			is.close();

		    } catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		    }
		}

	    }

	}
	return str;

    }

    /**
     * 组装请求字符串
     * 
     * @param request
     */
    public void geturl(String request) {

	StringBuffer sb = new StringBuffer("http://");
	sb.append(sp.getValue(XmlNameHelper.IP)).append(":").append(sp.getValue(XmlNameHelper.port));
	sb.append("/").append("WaterService").append(request);
	this.urlAddress = sb.toString();
	System.out.println(urlAddress);

    }

}
